package com.sky.service.user.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;

import com.sky.exception.OrderBusinessException;
import com.sky.mapper.user.*;
import com.sky.result.PageResult;
import com.sky.service.user.OrdersService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;


import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

@Slf4j
@Service("userOrdersService")
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */

    @Transactional
    @Override
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {

        Long currentId = BaseContext.getCurrentId();
        AddressBook addressBook = addressBookMapper.selectByIdOnly(currentId);
//        AddressBook addressBook = addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        User user = userMapper.selectById(currentId);
        log.info("根据用户id查询地址{}",addressBook);
        if (addressBook == null ){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        // 向订单表插入数据
        Orders orders = Orders.builder()
                .number(String.valueOf(System.currentTimeMillis()))
                .status(Orders.PENDING_PAYMENT)
                .userId(currentId)
                .orderTime(LocalDateTime.now())
                .payStatus(Orders.UN_PAID)
                .consignee(addressBook.getConsignee())
                .phone(addressBook.getPhone())
                .address(addressBook.getDetail())
                .build();

        BeanUtils.copyProperties(ordersSubmitDTO, orders);

        orders.setAddressBookId(addressBook.getId());
        ordersMapper.insert(orders);
        // 获取订单id ，添加到详情表，用于连接
        Long ordersId = orders.getId();

        // 获取购物车信息根据id
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(currentId)
                .build();
        log.info("查询条件为{}",shoppingCart);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.select(shoppingCart);
        log.info("shoppingCut的内容为{}",shoppingCartList);

        // 向订单详情表插入数据
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(ordersId);
            orderDetail.setId(null);
            log.info("向订单详情表中插入数据{}",orderDetail);
            ordersMapper.insertBatch(orderDetail);
        }

        shoppingCartMapper.deleteAll(currentId);
        // 清理购物车数据

        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();
        return orderSubmitVO;
    }

    /**
     * 订单支付
     * @param ordersPaymentDTO
     * @return
     */
    @Override
    public OrderPaymentVO paymentOrder(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.selectById(userId);
//        // 将构造的数据传入获得返回值
//        JSONObject jsonObject = weChatPayUtil.pay(ordersPaymentDTO.getOrderNumber(), new BigDecimal(0.01), "订单支付测试", user.getOpenId());
//        // 获取返回值中的code字段， 如果code 不为空并且code提示已支付的话，抛出订单已支付异常
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")){
//            throw new OrderBusinessException("该订单已支付");
//
//        }
//        // 通过获取java文件对象
//        OrderPaymentVO javaObject = jsonObject.toJavaObject(OrderPaymentVO.class);
//        javaObject.setPackageStr(jsonObject.getString("package"));
//        return javaObject;
        paySuccess(ordersPaymentDTO.getOrderNumber());
        return new OrderPaymentVO();
    }


    /**
     * 支付成功，修改订单状态
     */
    public void paySuccess(String outTradeNo){
        Long userId = BaseContext.getCurrentId();
        Orders ordersDB = ordersMapper.selectNumberAndUserId(outTradeNo, userId);
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .checkoutTime(LocalDateTime.now())
                .payStatus(Orders.TO_BE_CONFIRMED)
                .status(Orders.TO_BE_CONFIRMED)
                .build();

        ordersMapper.update(orders);
        // 添加下单提醒
        HashMap<Object,Object> map = new HashMap();
        map.put("type", 1);
        map.put("orderId", orders.getId());
        map.put("content", "订单号：" + outTradeNo);

        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO selectOrderDetail(Long id) {
        // 根据订单id查询订单和详情
        Orders orders = ordersMapper.selectById(null, id, null, null).get(0);
        List<OrderDetail> orderDetails = orderDetailMapper.selectById(id);
        // 封装到vo
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders, orderVO);
        orderVO.setOrderDetailList(orderDetails);

        return orderVO;
    }

    /**
     * 历史订单查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult historyOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 查询订单表数据
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<OrderVO> selectPage = ordersMapper.selectPage(ordersPageQueryDTO);

        log.info("查询语句数据{}", selectPage);

        // 查询订单详情表数据
        List<OrderVO> result = selectPage.getResult();
        if (!ObjectUtils.isEmpty(result)) {
            List<OrderDetail> orderDetails = orderDetailMapper.selectById(result.get(0).getId());

            // 更新状态并设置订单详情
            result.forEach(orderVO -> {

                // 已经使用 task定时任务处理
//                long seconds = Duration.between(orderVO.getOrderTime(), LocalDateTime.now()).getSeconds();
//                if (seconds > 900 && orderVO.getStatus().equals(Orders.PAID)) {
//                    orderVO.setStatus(Orders.CANCELLED);
//                }

                orderVO.setOrderDetailList(orderDetails);
            });
        }

        // 封装
        log.info("查询语句数据end{},{}", selectPage.getTotal(), selectPage.getResult());
        return new PageResult(selectPage.getTotal(), selectPage.getResult());
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {

        // 根据订单id查询出详情数据
        List<OrderDetail> orderDetails = orderDetailMapper.selectById(id);
        ShoppingCart shoppingCart = ShoppingCart.builder()
                .userId(BaseContext.getCurrentId())
                .createTime(LocalDateTime.now())
                .build();

        // 将对应数据插入到购物车
        for (OrderDetail orderDetail : orderDetails) {
            log.info("插入的购物车数据为{}", orderDetail);
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCartMapper.insert(shoppingCart);
        }


    }

    /**
     * 取消订单
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        Orders orders = Orders.builder()
                .id(id)
                .status(Orders.CANCELLED)
                .payStatus(Orders.REFUND)
                .cancelTime(LocalDateTime.now())
                .build();

        // 修改状态
        ordersMapper.update(orders);
    }

    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        // todo 催单逻辑
        // 查询订单是否存在
        Orders orders = ordersMapper.selectById(null, id, null, null).get(0);

        if (ObjectUtils.isEmpty(orders)){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 使用websocket发送催单消息
        HashMap<Object, Object> map = new HashMap<>();
        map.put("type", 2);
        map.put("orderId", id);
        map.put("content","订单号: "+orders.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));


    }
}
